package uade.distribuidas.server.dao;


import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import uade.distribuidas.repo.exception.ExceptionRemito;
import uade.distribuidas.repo.type.EstadoRemitoType;
import uade.distribuidas.server.domain.Remito;
import uade.distribuidas.server.domain.RemitoCPR;
import uade.distribuidas.server.domain.RemitoODV;
import uade.distribuidas.server.hibernate.HibernateUtil;

public class RemitosDAO {

	private static RemitosDAO instancia = null;
	private static SessionFactory sf = null;

	public static RemitosDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new RemitosDAO();
		} 
		return instancia;
	}
	
	@SuppressWarnings("unchecked")
	public List<Remito> getRemitos()throws ExceptionRemito{
		Session session = sf.openSession();
		
		List<Remito> lista = session.createQuery("from Remito").list();		
	
		
		session.close();
		return lista;
	}
	
	
	public Remito getRemito(Integer id)throws ExceptionRemito{
		Session session = sf.openSession();
		
		Remito r = (Remito) session.createQuery("from Remito where id = :id")
				.setParameter("id", id)
				.uniqueResult();			
		
		session.close();
		return r;
	}

	public Remito save(Remito r)throws ExceptionRemito {
		Session session = sf.openSession();
		 Transaction transaction = session.beginTransaction();
		 transaction.begin();
		 session.saveOrUpdate(r);
		 transaction.commit();
		 session.close();
		 return r;
	}

	public List<RemitoCPR> getRemitosCPR() {
		Session session = sf.openSession();
		
		@SuppressWarnings("unchecked")
		List<RemitoCPR> lista = (List<RemitoCPR>)session.createQuery("from RemitoCPR").list();		
	
		
		session.close();
		return lista;
	}

	public List<RemitoODV> getRemitosNoFacturados() {
		Session session = sf.openSession();
		
		@SuppressWarnings("unchecked")
		List<RemitoODV> lista = (List<RemitoODV>)session.createQuery("from RemitoODV where estado = :estado")
				.setParameter("estado", EstadoRemitoType.PEDIENTE)
				.list();		
	
		
		session.close();
		return lista;
	}
	

}
